<?php

namespace App\Api\Traits;

use Illuminate\Http\JsonResponse;

trait ApiResponseTrait
{
    public function responseData(string $message = '', int $code, $datas, $status, $errors = null, $headers = [], $options = 0): JsonResponse
    {
        $result = [
            'status' => $status,
            'code' => $code,
            'message' => $message,
            'data' => $datas,
            'result' => $status === 'success'];
        if ($errors) {
            $result['error'] = $errors;
            return response()->json($result, $code, $headers, $options);
        }
        return response()->json($result);
    }

    public function success(string $message = "request success", $datas = "", int $code = 200): JsonResponse
    {
        return $this->responseData(message: $message, code: config('api-response.success_code') ?: 200, datas: $datas, status: "success");
    }

    public function fail(string $message = "request fail", $code = 500): JsonResponse
    {
        $message = $this->enumCodeExist($code, $message);
        return $this->responseData(message: $message, code: $code, datas: null, status: "fail");
    }

    public function error(string $message = "request error", $code = 400, $error = null, $headers = [], $options = 0): JsonResponse
    {
        $message = $this->enumCodeExist($code, $message);
        return $this->responseData(message: $message, code: $code, datas: null, status: "error", errors: $error);
    }

    public function datas($datas, $message = ""): JsonResponse
    {
        return $datas ? $this->success(message: $message, datas: $datas) : $this->fail();
    }

    /**
     * 判断code是否存在于配置文件--针对于lang配置
     * @param $code
     * @param $message
     * @return mixed
     */
    public function enumCodeExist($code, $message): mixed
    {
        if (class_exists($enumClass = config('api-response.enum')) && $enumClass::hasValue($code)) {
            $enumResponse = $enumClass::fromValue($code);
            return $message ?: $enumResponse->description;
        }
        return $message;
    }
}
